<template>
  <div class="regist-component">
    <div class="title">
      账号注册
      <!-- <div class="close-regist">
        <Icon type="md-close-circle" size="30" />
      </div> -->
    </div>
    <!-- <div
      class="steps-header"
      :class="[current === 1 ? 'one' : current === 2 ? 'two' : 'three']"
    >
      <div class="steps steps-one">1</div>
      <div class="line line-one"></div>
      <div class="steps steps-two">2</div>
      <div class="line line-two"></div>
      <div class="steps steps-three">3</div>
    </div> -->
		<div
		  class="steps-header"
		  :class="[current === 1 ? 'one' : 'two' ]"
		>
		  <div class="steps steps-one">1</div>
		  <div class="line line-one"></div>
		  <div class="steps steps-two">2</div>
		  <!-- <div class="line line-two"></div>
		  <div class="steps steps-three">3</div> -->
		</div>
<!--    <div
      class="steps-title"
      :class="[current === 1 ? 'one' : current === 2 ? 'two' : 'three']"
    >
      <div class="title title-one">用户注册</div>
      <div class="title title-two">安全验证</div>
      <div class="title title-three">完成设置</div>
    </div> -->
	<div
	  class="steps-title"
	  :class="[current === 1 ? 'one' :'two']"
	>
	  <div class="title title-one">用户注册</div>
	  <div class="title title-three">完成设置</div>
	</div>
    <div class="regist-content" v-show="current === 1">
      <i-form ref="form-custom" :model="formCustom" :rules="ruleCustom">
        <Form-item prop="email" v-if="web_info.VERIFY_TYPE == 0">
          <i-input
            v-model="formCustom.email"
            :placeholder="$t('locale.pc.regist.t5')"
          ></i-input>
        </Form-item>
        <Form-item prop="username">
          <i-input
            v-model="formCustom.username"
            :placeholder="$t('locale.pc.regist.t6')"
          ></i-input>
        </Form-item>
        <Form-item prop="phone" v-if="web_info.VERIFY_TYPE == 1">
          <i-input
            v-model="formCustom.phone"
            :placeholder="$t('locale.pc.regist.t7')"
          ></i-input>
        </Form-item>
        <Form-item prop="password">
          <i-input
            v-model="formCustom.password"
            type="password"
            :placeholder="$t('locale.pc.regist.t8')"
          ></i-input>
        </Form-item>
        <Form-item prop="passwdCheck">
          <i-input
            v-model="formCustom.passwdCheck"
            type="password"
            :placeholder="$t('locale.pc.regist.t9')"
          ></i-input>
          <p>{{ $t("locale.pc.regist.t10") }}</p>
        </Form-item>
        <FormItem>
          <Checkbox v-model="is_agree">
            {{ $t("locale.pc.regist.t11") }}
            <nuxt-link to="/protocol">{{ $t("locale.pc.regist.t12") }}</nuxt-link>{{ $t("locale.pc.regist.t13") }}
            <nuxt-link to="/privacy">{{ $t("locale.pc.regist.t14") }}</nuxt-link>
          </Checkbox>
        </FormItem>
      </i-form>
      <div class="next-btn" :class="[is_agree ? 'active' : '']" @click="next">
        下一步
      </div>
      <div class="tologin">
        已有账号？<nuxt-link to="/login"
          ><span class="login">去登陆</span></nuxt-link
        >
      </div>
    </div>
    <!-- <div class="regist-content" v-show="current === 2">
      <div class="email-phone" v-if="web_info.VERIFY_TYPE == 0">
        邮箱：{{formCustom.email}}
      </div>
      <div class="email-phone" v-if="web_info.VERIFY_TYPE == 1">
        手机：{{formCustom.phone}}
      </div>
      <i-form ref="checkform" :rules="ruleCustom1" :model="formCustom1">
        <Form-item v-if="web_info.VERIFY_TYPE == 0">
          <i-input
            v-model="formCustom.email"
            class="emailvalidation"
            :placeholder="$t('locale.pc.regist.t20')"
            :disabled="true"
          ></i-input>
        </Form-item>
        <Form-item v-if="web_info.VERIFY_TYPE == 1">
          <i-input
            v-model="formCustom.phone"
            class="emailvalidation"
            :placeholder="$t('locale.pc.regist.t49')"
            :disabled="true"
          ></i-input>
        </Form-item>
        <Form-item prop="user_code">
          <i-input
            type="text"
            style="width: 300px !important"
            :placeholder="$t('locale.pc.regist.t21')"
            v-model="formCustom1.user_code"
          ></i-input>
          <Button
            class="verification"
            type="primary"
            v-if="web_info.VERIFY_TYPE == 0"
            @click.stop="sendEmailCode"
            :disabled="seconds !== 0"
            >{{
              seconds !== 0
                ? seconds + $t("locale.pc.regist.t22")
                : $t("locale.pc.regist.t23")
            }}</Button
          >
          <Button
            class="verification"
            type="primary"
            v-if="web_info.VERIFY_TYPE == 1"
            @click.stop="sendPhoneCode"
            :disabled="seconds !== 0"
            >{{
              seconds !== 0
                ? seconds + $t("locale.pc.regist.t22")
                : $t("locale.pc.regist.t23")
            }}</Button
          >
        </Form-item>
        <FormItem>
          <Button class="nextstep" type="primary" @click="next">{{
                      $t("locale.pc.regist.t24")
                    }}</Button>
          <Button class="nextstep" type="primary" @click="preStep">上一步</Button>
          <div class="toregist">
            <p class="link">
              {{ $t("locale.pc.regist.t25") }}
              <nuxt-link to="/login">
                {{ $t("locale.pc.regist.t26") }}
                <span>{{ $t("locale.pc.regist.t27") }}</span>
              </nuxt-link>
            </p>
          </div>
        </FormItem>
      </i-form>
      <div class="next-btn" :class="[is_agree ? 'active' : '']" @click="next">
        下一步
      </div>
      <div class="tologin">
        已有账号？<nuxt-link to="/login"
          ><span class="login">去登陆</span></nuxt-link
        >
      </div>
    </div> -->
    <div class="regist-content" v-show="current === 2">
      <div class="regist-done">
        <div class="icons">
          <Icon type="ios-checkmark-circle" />
        </div>
        <div class="success-text">恭喜您，已完成注册</div>
        <div class="other-text">
          用户{{
            user_info.email
          }}
          恭喜您已完成了用户注册，可以开始学习啦。系统将在{{
            seconds
          }}秒内自动跳转，如若未进行跳转，请<a @click="$router.replace('/')"
            >点击跳转</a
          >
        </div>
      </div>
    </div>
    <!-- <Button type="primary" @click="next">Next step</Button> -->
  </div>
</template>
<script>
import {
  getEmailCode,
  userRegist,
  userLogin,
  getSmsCode
} from "~/api/account/user.js";
import { mapMutations, mapState } from "vuex";
import { strToHexCharCode, hexCharCodeToStr } from "~/utils/commonfun";
export default {
  data() {
    //   验证邮箱
    var email = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    // 验证电话号码
    var phone = /^1(3|4|5|6|7|8|9)\d{9}$/;
    // 验证密码格式
    // var pass = /^([a-zA-Z]|[0-9][\S,.!@$^&*-=+`~?:;]).{6,16}$/;
    var pass = /^[\d_a-zA-Z_,.!@$^&%*-=+`~?:;]{6,16}$/;
    const validateemail = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("locale.pc.regist.t35")));
      } else if (!email.test(value)) {
        callback(new Error(this.$t("locale.pc.regist.t36")));
      }
      callback();
    };

    const validateusername = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("locale.pc.regist.t37")));
      }
      callback();
    };

    const validatephone = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("locale.pc.regist.t38")));
      } else if (!phone.test(value)) {
        callback(new Error(this.$t("locale.pc.regist.t39")));
      }
      callback();
    };

    const validatepassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("locale.pc.regist.t40")));
      } else if (!pass.test(value)) {
        callback(new Error(this.$t("locale.pc.regist.t41")));
      }
      callback();
    };

    const validatepasswdCheck = (rule, value, callback) => {
      if (value == "") {
        callback(new Error(this.$t("locale.pc.regist.t42")));
      } else if (value !== this.formCustom.password) {
        callback(new Error(this.$t("locale.pc.regist.t43")));
      }
      callback();
    };
    return {
      current: 1,
      actived_key: "1",
      // key: 1,
      formCustom: {
        email: "",
        username: "",
        phone: "",
        password: "",
        passwdCheck: "",
        regulations: false
      },
      ruleCustom: {
        email: [{ validator: validateemail, trigger: "change" }],
        username: [{ validator: validateusername, trigger: "change" }],
        phone: [{ validator: validatephone, trigger: "change" }],
        password: [{ validator: validatepassword, trigger: "change" }],
        passwdCheck: [{ validator: validatepasswdCheck, trigger: "change" }]
      },
      ruleCustom1: {
        user_code: [
          {
            validator: (rule, value, callback) => {
              if (value == "") {
                callback(new Error(this.$t("locale.pc.regist.t44")));
              } else if (this.code == "") {
                callback(new Error("请先点击发送验证码"));
              } else if (!this.code.test(value)) {
                callback(new Error(this.$t("locale.pc.regist.t45")));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ]
      },
      is_agree: false,
      code: "", //短信验证码
      formCustom1: {
        user_code: "" //用户填写的验证码
      },
      interval: null,
      seconds: 0
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      web_info(state) {
        return state.web_info;
      }
    }),
    classCoding() {
      return this.$route.query.coding;
    },
  },
  created() {},
  mounted() {},
  methods: {
    ...mapMutations([
      "SET_IS_LOADING",
      "SET_TOKEN",
      "SET_USERINFO",
      "SET_LOGINTYPE"
    ]),
    handleSelect(key) {
      this.key += 1;
    },
    sendEmailCode() {
      getEmailCode({
        to: this.formCustom.email
      }).then(result => {
        if (result && result.data && result.data.code == 200) {
          this.code = new RegExp(hexCharCodeToStr(result.data.data.code));
          this.seconds = 60;
          this.cuntDown();
        } else {
          this.$Message.error({
            type: "danger",
            message: this.$t("locale.pc.regist.t46")
          });
        }
      });
    },
    sendPhoneCode() {
      getSmsCode({
        number: this.formCustom.phone
      }).then(result => {
        if (result && result.data && result.data.code == 200) {
          this.code = new RegExp(hexCharCodeToStr(result.data.data.RequestId));
          this.seconds = 60;
          this.cuntDown();
        } else {
          this.$Message.error($t("locale.mobile.regist.t35"));
        }
      });
    },
    onSubmit() {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        let fatherId = 0;
        if (this.$route.query.fatherId) {
          fatherId = this.$route.query.fatherId;
        }
        const { email, password, phone, username } = this.formCustom;
        let params = {
          email: email,
          password,
          mobile: phone,
          acName: username,
          fatherId,
          ip: returnCitySN.cip
        }
        if (this.classCoding) {
          params = {
            ...params,
            coding:this.classCoding
          }
        }
        userRegist(params).then(async res => {
          if (res && res.data && res.data.code == 200) {
            // 由于班级邀请码注册用户需要审核，所以注册完成跳转登录
            if(this.classCoding){
              this.$Message.success("注册成功！");
              this.$router.replace("/login");
              return;
            }
            let result = await this.handleLogin();
            if (result === "success") {
              // this.$Message.success("注册成功！");
              // this.$router.replace("/m");
              resolve("success");
            } else {
              this.$Message.error(
                this.$t("locale.pc.regist.t47") +
                  (result && result.data && result.data.msg)
              );
              reject("faild");
            }
          } else {
            let msg = res && res.data && res.data.msg;
            this.$Message.error(this.$t("locale.pc.regist.t48") + msg);
            reject("faild");
          }
        });
      });
    },
    handleLogin() {
      return new Promise(async (res, rej) => {
        let param = {
          password: this.formCustom.password
        };
        if (this.web_info.VERIFY_TYPE == 1) {
          param = {
            ...param,
            account: this.formCustom.phone
          };
        } else if (this.web_info.VERIFY_TYPE == 0) {
          param = {
            ...param,
            email: this.formCustom.email
          };
        }
        let result = await userLogin(param);
        if (result && result.data && result.data.code === 200) {
          this.SET_TOKEN(result.headers.authorization);
          this.SET_USERINFO(result.data.data);
          if (this.web_info.VERIFY_TYPE == 1) {
            this.SET_LOGINTYPE("mobile");
          } else if (this.web_info.VERIFY_TYPE == 0) {
            this.SET_LOGINTYPE("email");
          }
          res("success");
        } else {
          rej(result.data.msg);
        }
      }).catch(e => {
        if (e) {
          this.SET_IS_LOADING(false);
        }
      });
    },
    cuntDown(type) {
      this.interval = setInterval(() => {
        this.seconds--;
        if (this.seconds <= 0) {
          this.seconds = 0;
          if (type == "success") {
            this.$router.replace("/");
          }
          clearInterval(this.interval);
        }
      }, 1000);
    },
    preStep() {
      if (this.current == 1) {
        return;
      } else {
        this.current -= 1;
        this.actived_key = String(Number(this.actived_key) - 1);
      }
    },
    next() {
      if (!this.is_agree) {
        return;
      }
      if (this.current == 1) {
        this.$refs["form-custom"].validate(async valid => {
          if (valid && this.is_agree) {
            if (this.current == 2) {
              this.current = 1;
              this.actived_key = "1";
            } else {
				let result = await this.onSubmit().then();
				if (result == "success") {
				  this.current += 1;
				  this.actived_key = String(Number(this.actived_key) + 1);
				  this.interval = null;
				  this.seconds = 10;
				  this.cuntDown("success");
				} else {
				  return;
				}
              
            }
          } else {
            return;
          }
        });
      }
      if (this.current == 2) {
        console.log("第二页");
        // if(this.formCustom1.user_code!="" && !this.code.test(this.formCustom1.user_code))
        // console.log(this.$refs["checkform"].validate);
        this.$refs["checkform"].validate(async valid => {
          // console.log(this.formCustom1);
          // console.log(this.$refs["checkform"]);
          // console.log(valid);
          if (valid) {
            console.log("验证通过");
            let result = await this.onSubmit().then();
            if (result == "success") {
              if (this.current == 3) {
                this.current = 1;
                this.actived_key = "1";
              } else {
                this.current += 1;
                this.actived_key = String(Number(this.actived_key) + 1);
              }
              this.interval = null;
              this.seconds = 10;
              this.cuntDown("success");
            } else {
              return;
            }
          } else {
            return;
          }
        });
      }
      // if (this.current == 2) {
      //   console.log("第三页");
      //   this.$router.replace("/");
      // }
      //   if (this.current == 3) {
      //     this.current = 3;
      //   } else {
      //     this.current += 1;
      //   }
    }
  }
};
</script>
<style lang="scss">
.ivu-form-item {
  // margin-bottom: 16px;
}
</style>
<style lang="scss" scoped>
.regist-component {
  width: 800px;
  height: 600px;
  margin: 0 auto;

  .title {
    font-size: 22px;
    text-align: center;
    line-height: 40px;
    font-weight: bold;
    color: #46494e;
    padding: 10px 0;
    position: relative;
    .close-regist {
      cursor: pointer;
      position: absolute;
      right: 20px;
      top: 6px;
      opacity: 0.5;
    }
  }
  .steps-title {
    width: 434px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .title {
      width: 54px;
      font-size: 13px;
      text-align: center;
      color: #c3d7fc;
    }
  }
  .steps-title.one {
    .title-one {
      color: var(--theme-color);
    }
  }
  .steps-title.two {
    .title-one {
      color: var(--theme-color);
    }
    .title-two {
      color: var(--theme-color);
    }
  }
  .steps-title.three {
    .title-one {
      color: var(--theme-color);
    }
    .title-two {
      color: var(--theme-color);
    }
    .title-three {
      color: var(--theme-color);
    }
  }

  .steps-header {
    width: 434px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .steps {
      width: 54px;
      height: 54px;
      line-height: 54px;
      text-align: center;
      background-color: #c3d7fc;
      font-size: 24px;
      color: #ffffff;
      border-radius: 50%;
    }
    .line {
      width: 110px;
      height: 2px;
      background-color: #c3d7fc;
      margin: 0 10px;
    }
  }
  .steps-header.one {
    .steps-one {
      background-color: var(--theme-color);
    }
    // .line-one{
    //     background-color:var(--theme-color);
    // }
  }
  .steps-header.two {
    .steps-one {
      background-color: var(--theme-color);
    }
    .line-one {
      background-color: var(--theme-color);
    }
    .steps-two {
      background-color: var(--theme-color);
    }
  }
  .steps-header.three {
    .steps-one {
      background-color: var(--theme-color);
    }
    .line-one {
      background-color: var(--theme-color);
    }
    .steps-two {
      background-color: var(--theme-color);
    }
    .line-two {
      background-color: var(--theme-color);
    }
    .steps-three {
      background-color: var(--theme-color);
    }
  }
  .regist-content {
    width: 434px;
    margin: 0 auto;
    .regist-done {
      .icons {
        margin: 40px auto 0;
        text-align: center;
        > i {
          color: var(--theme-color);
          font-size: 120px;
        }
      }
      .success-text {
        margin-top: 18px;
        color: #5b6069;
        font-size: 20px;
        // font-weight: bolder;
        text-align: center;
        font-family: SourceHanSansSC-bold;
      }
      .other-text {
        color: #a2a8b3;
        font-size: 14px;
        text-align: left;
        font-family: SourceHanSansSC-regular;
        line-height: 30px;
        > a {
          color: var(--theme-color);
        }
      }
    }
    .email-phone {
      line-height: 20px;
      font-size: 16px;
      padding: 10px 0;
    }
    .next-btn {
      width: 100%;
      height: 55px;
      text-align: center;
      cursor: pointer;
      background-color: #91b8fc;
      border-radius: 28px;
      font-size: 20px;
      font-weight: bold;
      line-height: 55px;
      color: #ffffff;
    }
    .next-btn.active {
      background-color: var(--theme-color);
    }
    .tologin {
      font-size: 14px;
      padding: 10px 0;
      .login {
        color: var(--theme-color);
        font-size: 14px;
        cursor: pointer;
      }
      .login:hover {
        text-decoration: underline;
      }
    }
  }
}
</style>
